package cn.duxiaod.springbootdubboprovider.service.impl;

import cn.duxiaod.dubbo.api.service.CostService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.apache.dubbo.config.annotation.Service;

import java.util.Random;

/**
 * 注意使用alibaba注解：org.apache.dubbo.config.annotation.DubboService
 */
@Service(version = "${dubbo.service.version}")
public class CostServiceImpl implements CostService {
    /**
     * 假设之前总花费了100
     */
    private final Integer totalCost = 1000;

    /**
     * 之前总和 加上 最近一笔
     * @param cost
     * @return
     */
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
    })
    @Override
    public Integer add(int cost) {
        /**
         * Hystrix超时配置为2s，实现类超过2s，服务调用者将执行服务降级函数
         */
        int nextInt = new Random().nextInt(4000);
        System.out.println("sleep " + nextInt + "ms");
        try {
            Thread.sleep(nextInt);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return totalCost + cost;
    }
}
